package com.mike.blog.controller;

import com.mike.blog.form.LoginForm;
import com.mike.blog.service.LoginService;
import common.lib.core.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @author xiaozefeng
 * @date 12/12/18 11:40 PM
 */
@Controller
@RequestMapping("/")
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 跳转登录页
     */
    @GetMapping("login")
    public String toLogin() {
        return "login";
    }


    /**
     * 请求请求
     */
    @PostMapping("login")
    @ResponseBody
    public ResultVO login(HttpServletResponse response, @Valid LoginForm loginForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultVO.error(bindingResult.getFieldError().getDefaultMessage());
        }
        log.info("login form: {}", loginForm);
        if (!loginService.login(response, loginForm)) {
            return ResultVO.error("登录失败");
        }
        return ResultVO.ok();
    }

}
